﻿#region [OutOfBrowser Using Statements]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using ControlPanelOOB.AccelerometerService;
using System.Windows.Threading;
using System.ServiceModel;
using ControlPanelOOB;
using PivotControlOOWP;
#endregion

namespace ControlPanelOOB
{
    /// <summary>
    /// UserControl loaded if the application is running out of the browser (OOB)
    /// </summary>
    public partial class OutOfBrowser : UserControl
    {
        #region [OutOfBrowser Properties]
        private DispatcherTimer CheckXNATimer { get; set; }
        private DispatcherTimer WaitBeforeCheckingXNATimer { get; set; }
        private DispatcherTimer WaitBeforeLoadPivotTimer { get; set; }
        private DispatcherTimer PollingServerTimer { get; set; }
        private AccelerometerServiceClient AccelerometerService { get; set; }
        private Pivot PivotControl { get; set; }
        StartUpPage StartUpPage { get; set; }
        #endregion

        #region [OutOfBrowser Constructor]
        /// <summary>
        /// OutOfBrowser Constructor]
        /// </summary>
        public OutOfBrowser()
        {
            InitializeComponent();

            BasicHttpBinding basicHttpBinding = new BasicHttpBinding();
            EndpointAddress endpointAddress = new EndpointAddress("http://localhost:8731/AccelerometerServer/");
            AccelerometerService = new AccelerometerServiceClient(basicHttpBinding, endpointAddress);
            AccelerometerService.GetXNAStatusCompleted += new EventHandler<GetXNAStatusCompletedEventArgs>(AccelerometerService_GetXNAStatusCompleted);
            AccelerometerService.DownloadAccelDataCompleted += new EventHandler<DownloadAccelDataCompletedEventArgs>(AccelerometerService_DownloadAccelDataCompleted);
            AccelerometerService.DownloadRotationDataCompleted += new EventHandler<DownloadRotationDataCompletedEventArgs>(AccelerometerService_DownloadRotationDataCompleted);

            StartUpPage = new StartUpPage();
            StartUpPage.PageLoaded += new StartUpPage.PageLoadedEventHandler(StartUpPage_PageLoaded);
            LayoutRoot.Children.Add(StartUpPage);
        }
        #endregion

        #region [OutOfBrowser EventHandlers]
        /// <summary>
        /// Event handler triggered when the StartUpPage PageLoaded event is triggered
        /// </summary>
        /// <param name="sender">Who triggered the event handler</param>
        /// <param name="e">Defaul EventArgs</param>
        void StartUpPage_PageLoaded(object sender, EventArgs e)
        {
            //Check for the Windows Phone 7 XNA Accelerometer Simulator app every 2 secs
            WaitBeforeCheckingXNATimer = new DispatcherTimer();
            WaitBeforeCheckingXNATimer.Interval = new TimeSpan(0, 0, 2);
            WaitBeforeCheckingXNATimer.Tick += new EventHandler(WaitBeforeCheckingXNATimer_Tick);
            WaitBeforeCheckingXNATimer.Start();
        }
        
        /// <summary>
        /// Event Handler triggered then the GetXNAStatus service call completes
        /// </summary>
        /// <param name="sender">Who triggered the event</param>
        /// <param name="e">
        /// GetXNAStatus EventArgs, the Result is a boolean indicating if the 
        /// Windows Phone 7 XNA Accelerometer Simulator is running or not
        /// </param>
        private void AccelerometerService_GetXNAStatusCompleted(object sender, GetXNAStatusCompletedEventArgs e)
        {
            if (e.Result)
            {
                WaitBeforeCheckingXNATimer.Stop();
                StartUpPage.ChangeLoadingMessage("WP7 XNA Accelerometer Panel detected. Opening Control Panel");

                //Wait 2 seconds before loading the Pivot Control so the user can read the Panel detected message
                //we just set the line before
                WaitBeforeLoadPivotTimer = new DispatcherTimer();
                WaitBeforeLoadPivotTimer.Interval = new TimeSpan(0, 0, 2);
                WaitBeforeLoadPivotTimer.Tick += new EventHandler(WaitBeforeLoadPivotTimer_Tick);
                WaitBeforeLoadPivotTimer.Start();
            }
        }

        /// <summary>
        /// Event handler triggered when the DownloadAccelData service call completes
        /// </summary>
        /// <param name="sender">Who triggered the event</param>
        /// <param name="e">
        /// DownloadAccelData EventArgs: XYZData object representing WP7 acceleraiton 
        /// over the X, Y and Z axis
        /// </param>
        private void AccelerometerService_DownloadAccelDataCompleted(object sender, DownloadAccelDataCompletedEventArgs e)
        {
            XYZData accelData = e.Result;
            PivotControl.ChangePivotSubItemDescription("acceleration", "X Axis", accelData.X.ToString());
            PivotControl.ChangePivotSubItemDescription("acceleration", "Y Axis", accelData.Y.ToString());
            PivotControl.ChangePivotSubItemDescription("acceleration", "Z Axis", accelData.Z.ToString());
        }

        /// <summary>
        /// Event handler triggered twhen the DownloadRotationData service call completes
        /// </summary>
        /// <param name="sender">Who triggered the event</param>
        /// <param name="e">
        /// DownloadAccelData EventArgs: XYZData object representing WP7 rotation 
        /// over the X, Y and Z axis
        /// </param>
        private void AccelerometerService_DownloadRotationDataCompleted(object sender, DownloadRotationDataCompletedEventArgs e)
        {
            XYZData rotData = e.Result;
            PivotControl.ChangePivotSubItemDescription("rotation", "X Axis", rotData.X.ToString());
            PivotControl.ChangePivotSubItemDescription("rotation", "Y Axis", rotData.Y.ToString());
            PivotControl.ChangePivotSubItemDescription("rotation", "Z Axis", rotData.Z.ToString());
        }

        /// <summary>
        /// Event handler triggered when the WaitBeforeLoadPivotTimer DispatchTimer ends
        /// </summary>
        /// <param name="sender">Who triggered the event</param>
        /// <param name="e">Default EventArgs</param>
        private void WaitBeforeLoadPivotTimer_Tick(object sender, EventArgs e)
        {
            WaitBeforeLoadPivotTimer.Stop();
            LoadPivot();
        }

        /// <summary>
        /// Event handler triggered when the WaitBeforeCheckingXNATimer DispatchTimer ends
        /// </summary>
        /// <param name="sender">Who triggered the event</param>
        /// <param name="e">Default EventArgs</param>
        private void WaitBeforeCheckingXNATimer_Tick(object sender, EventArgs e)
        {
            AccelerometerService.GetXNAStatusAsync();

        }

        /// <summary>
        /// Event handler triggered when the PollingServerTimer DispatchTimer ends
        /// </summary>
        /// <param name="sender">Who triggered the event</param>
        /// <param name="e">Default EventArgs</param>
        private void PollingServerTimer_Tick(object sender, EventArgs e)
        {
            AccelerometerService.DownloadAccelDataAsync();
            AccelerometerService.DownloadRotationDataAsync();
        }
        #endregion

        #region [OutOfBrowser Private Methods]
        /// <summary>
        /// Loads the a Pivot look a like UserControl
        /// </summary>
        /// <remarks>
        /// The Pivot look a like UserControl is referenced by the PivotControl.dll
        /// whose namespace is PivtoControlOOWP (OOWP = out of windows phone)
        /// I plan to release the PivotControl code on codeplex when its more polished.
        /// </remarks>
        private void LoadPivot()
        {
            LayoutRoot.Children.Clear();
            BuildPivotControl();
            
            PollingServerTimer = new DispatcherTimer();
            PollingServerTimer.Tick += new EventHandler(PollingServerTimer_Tick);
            PollingServerTimer.Interval = new TimeSpan(0, 0, 0, 0, 50); //polling every 50 ms
            PollingServerTimer.Start();
        }

        /// <summary>
        /// Customizes the Pivot look a like UserControl
        /// </summary>
        /// <remarks>
        /// The Pivot look a like UserControl is referenced by the PivotControl.dll
        /// whose namespace is PivtoControlOOWP (OOWP = out of windows phone)
        /// I plan to release the PivotControl code on codeplex when its more polished.
        /// </remarks>
        private void BuildPivotControl()
        {
            PivotControl = new Pivot("ACCELEROMETER SIMULATOR CONTROL PANEL");

            PivotControl.AddPivotItem("acceleration","AccelWP480.png");
            PivotControl.AddPivotItem("rotation","RotationWP480.png");
            PivotControl.AddPivotItem("orientation","OrientationWP480.png");
            PivotControl.AddPivotSubItem("acceleration", "X Axis", "0");
            PivotControl.AddPivotSubItem("acceleration", "Y Axis", "0");
            PivotControl.AddPivotSubItem("acceleration", "Z Axis", "0");
            PivotControl.AddPivotSubItem("rotation", "X Axis", "0");
            PivotControl.AddPivotSubItem("rotation", "Y Axis", "0");
            PivotControl.AddPivotSubItem("rotation", "Z Axis", "0");
            PivotControl.AddPivotSubItem("orientation", "Not implemented yet", "It will let you set the phone to some default orientations");
            //PivotControl.AddPivotSubItem("orientation", "Flat on the desk - face up", "Not implemented yet");
            //PivotControl.AddPivotSubItem("orientation", "Flat on the desk - face down", "Not implemented yet");
            //PivotControl.AddPivotSubItem("orientation", "Tombstone - controls on the bottom", "Not implemented yet");
            //PivotControl.AddPivotSubItem("orientation", "Tombstone - controls on the top", "Not implemented yet");
            //PivotControl.AddPivotSubItem("orientation", "Landscape – controls on the right", "Not implemented yet");
            //PivotControl.AddPivotSubItem("orientation", "Landscape – controls on the left", "Not implemented yet");

            LayoutRoot.Children.Add(PivotControl);
        }
        #endregion
    }
}
